package com.example.demo.jpa.person.dao;

import com.example.demo.jpa.person.domain.Person;
import com.example.demo.jpa.person.dto.PersonCommand;
import com.example.demo.jpa.person.repo.PersonRepository;
import com.example.demo.jpa.person.dto.PersonDTO;
import jakarta.persistence.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.Optional;

import static java.util.Objects.isNull;


@Component
public class PersonDAO {

    @Autowired
    PersonRepository personRepository;

    public PersonDTO findPersonById(Long id){
        Optional<Person> pp = personRepository.findById(id);
        if(pp.isEmpty()){
            throw new RuntimeException("Person not found");
        }
        Person p = pp.get();
        PersonDTO dto = new PersonDTO(p.getId(),p.getName(),p.getAge());
        return dto;
    }

    public PersonDTO findPersonByName(String name){
        Person pp = personRepository.findByName(name);
        if(isNull(pp)){
            throw new RuntimeException("Person not found");
        }
        return new PersonDTO(pp.getId(),pp.getName(),pp.getAge());
    }

    public PersonDTO createPerson(PersonCommand personCommand){
        Person pp = new Person(personCommand.getName(),personCommand.getAge());
        Person tmp = personRepository.save(pp);
        return new PersonDTO(tmp.getId(),tmp.getName(),tmp.getAge());
    }


    public PersonDTO updatePerson(Long id, PersonCommand personCommand) {
        Optional<Person> pp = personRepository.findById(id);
        if(pp.isEmpty()){
            throw new RuntimeException("Person not found");
        }
        Person p = pp.get();
        if(personCommand.getName() != null){
            p.setName(personCommand.getName());
        }
        if(personCommand.getAge() != null){
            p.setAge(personCommand.getAge());
        }
        Person tmp = personRepository.save(p);
        return new PersonDTO(tmp.getId(),tmp.getName(),tmp.getAge());
    }

    public void deletePersonById(Long id) {
        Optional<Person> pp = personRepository.findById(id);
        if(pp.isEmpty()){
            throw new RuntimeException("not found");
        }else{
            personRepository.deleteById(id);
        }
    }
}
